package vn.edu.uit.chemistry;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Map;

import vn.edu.uit.chemistry.utilities.TCPClient;
import vn.edu.uit.chemistry.view.ViewRowKiemTra15;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class KiemTra15 extends Activity{
	
	ImageView imgTheoDoi;
	
	Button btnTinhGio;
	TextView tvGio;
	Button btnChamDiem;
	public static LinearLayout listKT15;
	CountDownTimer countDown;
	long totalTimeCountInMilliseconds;
	
	public String dapAn = "";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.screen_kiemtra15);
		
		
		dapAn = loadDapAn();
		
		imgTheoDoi = (ImageView) findViewById(R.id.imgTheoDoi);
		btnTinhGio = (Button) findViewById(R.id.btnTinhGio);
		btnTinhGio.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				guiKichHoat();
				tinhGio();
				btnTinhGio.setEnabled(false);
			}
		});
		
		tvGio = (TextView) findViewById(R.id.tvGio);
		btnChamDiem = (Button) findViewById(R.id.btnChamDiem);
		btnChamDiem.setEnabled(false);
		btnChamDiem.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				guiDapAn();
				//imgTheoDoi.removeCallbacks(onEverySecond);
			}
		});
		
		listKT15 = (LinearLayout) findViewById(R.id.listLamBai);
		imgTheoDoi.postDelayed(onEverySecond, 0);
		
		totalTimeCountInMilliseconds = 61 * 1000;
	}
	
//	public void luuFile() {
//
//		File sdcard = Environment.getExternalStorageDirectory().getAbsoluteFile();
//		File file = new File(sdcard,"/hoa hoc/kiem tra/kt15/dapan.txt");
//
//		FileOutputStream fos;
//		byte[] data = new String("GV-ABCDABCDABCDACC\nHS-ABCDABCDABCDACC").getBytes();
//		try {
//			fos = new FileOutputStream(file);
//			fos.write(data);
//			fos.flush();
//			fos.close();
//		} catch (FileNotFoundException e) {
//			// handle exception
//		} catch (IOException e) {
//			// handle exception
//		}
//	}
	
	public String loadDapAn() {
		File sdcard = Environment.getExternalStorageDirectory().getAbsoluteFile();
		File file = new File(sdcard,"/hoa hoc/kiem tra/kt15/dapan.txt");

		StringBuilder text = new StringBuilder();

		try {
		    BufferedReader br = new BufferedReader(new FileReader(file));
		    String line;

		    while ((line = br.readLine()) != null) {
		        text.append(line);
		        text.append('\n');
		    }
		}
		catch (IOException e) {
		    //You'll need to add proper error handling here
		}
	
		return text.toString().trim();
	}
	
	public void guiKichHoat() {
		SharedPreferences prefs = getSharedPreferences("DSLamBai", 0);
		Map<String, ?> keys = prefs.getAll();
		for (Map.Entry<String, ?> entry : keys.entrySet()) {
			
			new KichHoatAsyncTask(entry.getKey()).execute();
		}
	}
	
	final class KichHoatAsyncTask extends AsyncTask<Void, Void, Void> {
		
		Context ctx;
		String key = "";
		
		public KichHoatAsyncTask(String _key) {
			this.ctx = KiemTra15.this;
			this.key = _key;
		}

		@Override
		protected Void doInBackground(Void... params) {
			TCPClient client;
			try {
				client = new TCPClient(ctx, key, 54321);
				client.kichHoatLamKT15();
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
		
	}
	
	public void tinhGio() {
		countDown = new CountDownTimer(totalTimeCountInMilliseconds, 500) {

			@Override
			public void onTick(long millisUntilFinished) {
				long seconds = millisUntilFinished / 1000;
				tvGio.setText(String.format("%02d", seconds / 60) + ":"
						+ String.format("%02d", seconds % 60));
			}

			@Override
			public void onFinish() {
				btnChamDiem.setEnabled(true);
			}
		}.start();
	}
	
	public void guiDapAn() {
		SharedPreferences prefs = getSharedPreferences("DSLamBai", 0);
		Map<String, ?> keys = prefs.getAll();
		for (Map.Entry<String, ?> entry : keys.entrySet()) {
			new GuiDapAnAsyncTask(entry.getKey()).execute();
		}

//		SharedPreferences.Editor editor = prefs.edit();
//		editor.clear();
//		editor.commit();
	}
	
	final class GuiDapAnAsyncTask extends AsyncTask<Void, Void, Void> {
		
		Context ctx;
		String key = "";
		
		public GuiDapAnAsyncTask(String _key) {
			this.ctx = KiemTra15.this;
			this.key = _key;
		}

		@Override
		protected Void doInBackground(Void... params) {
			TCPClient client;
			try {
				client = new TCPClient(ctx, key, 54321);
				client.guiDapAnKT15(dapAn);
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
		
	}
	
	public Runnable onEverySecond = new Runnable() {
		public void run() {
			new UpdatePrecentAsyncTask(getApplicationContext()).execute();
		}
	};
	
	final class UpdatePrecentAsyncTask extends AsyncTask<Void, Void, Void> {

		private Context context;
		private ViewRowKiemTra15 viewKT15;
		private LayoutParams lp;
		private Map<String, ?> keys;

		public UpdatePrecentAsyncTask(Context ctx) {
			this.context = ctx;
		}

		@Override
		protected Void doInBackground(Void... param) {
			SharedPreferences prefs = getSharedPreferences("DSLamBai", 0);
			keys = prefs.getAll();
			return null;
		}

		@Override
		protected void onPostExecute(final Void unused) {
			listKT15.removeAllViews();
			for (Map.Entry<String, ?> entry : keys.entrySet()) {
				String[] values = entry.getValue().toString().split("#");
				viewKT15 = new ViewRowKiemTra15(context);
				viewKT15.setContent(values[1], values[0], Integer.parseInt(values[2]), Integer.parseInt(values[3]));
				listKT15.addView(viewKT15.layout);
			}
			imgTheoDoi.postDelayed(onEverySecond, 0);
		}

	}
}
